import 'package:equatable/equatable.dart';

/// 群聊模型
/// 使用Equatable实现相等性比较
class ChatGroupModel extends Equatable {
  /// 群聊ID
  final String id;

  /// 群聊标题
  final String title;

  /// 群聊详情文字
  final String description;

  /// 群聊封面图片路径
  final String coverImage;

  /// 创建者用户ID
  final String creatorId;

  /// 创建时间
  final DateTime createTime;

  /// 加入用户的ID列表
  final List<String> memberIds;

  const ChatGroupModel({
    required this.id,
    required this.title,
    required this.description,
    required this.coverImage,
    required this.creatorId,
    required this.createTime,
    this.memberIds = const [],
  });

  /// 从JSON创建群聊对象
  factory ChatGroupModel.fromJson(Map<String, dynamic> json) {
    return ChatGroupModel(
      id: json['id'] as String,
      title: json['title'] as String,
      description: json['description'] as String,
      coverImage: json['coverImage'] as String,
      creatorId: json['creatorId'] as String,
      createTime: DateTime.parse(json['createTime'] as String),
      memberIds: List<String>.from(json['memberIds'] as List? ?? []),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'coverImage': coverImage,
      'creatorId': creatorId,
      'createTime': createTime.toIso8601String(),
      'memberIds': memberIds,
    };
  }

  /// 复制并修改部分属性
  ChatGroupModel copyWith({
    String? id,
    String? title,
    String? description,
    String? coverImage,
    String? creatorId,
    DateTime? createTime,
    List<String>? memberIds,
  }) {
    return ChatGroupModel(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      coverImage: coverImage ?? this.coverImage,
      creatorId: creatorId ?? this.creatorId,
      createTime: createTime ?? this.createTime,
      memberIds: memberIds ?? this.memberIds,
    );
  }

  /// 验证群聊数据是否有效
  bool get isValid {
    return title.isNotEmpty &&
        description.isNotEmpty &&
        coverImage.isNotEmpty &&
        creatorId.isNotEmpty;
  }

  /// 获取成员数量
  int get memberCount => memberIds.length;

  /// 检查用户是否已加入
  bool isUserJoined(String userId) {
    return memberIds.contains(userId);
  }

  @override
  List<Object?> get props => [
    id,
    title,
    description,
    coverImage,
    creatorId,
    createTime,
    memberIds,
  ];

  @override
  String toString() {
    return 'ChatGroupModel(id: $id, title: $title, creatorId: $creatorId, memberCount: $memberCount)';
  }
}
